import { createEntityAdapter, createSlice, Draft, EntityState, PayloadAction } from "@reduxjs/toolkit";
import { AppState } from "@store/index";
import type { EntityId } from "@reduxjs/toolkit";

// 创建搜索结果状态实体适配器
//@ts-ignore
const searchEntityAdaptor = createEntityAdapter<News>({
    selectId: (news) => news.art_id,
});

// 创建用于管理搜索结果的状态切片
const { reducer: searchReducer, actions } = createSlice<
    EntityState<News, EntityId>,
    {
        // 保存搜索结果
        saveResults(
            state: Draft<EntityState<News, EntityId>>,
            action: PayloadAction<News[]>
        ): void;
        // 清空搜索结果
        clearResults(state: Draft<EntityState<News, EntityId>>): void;
    },
    "search",
    never
>({
    name: "search",
    initialState: searchEntityAdaptor.getInitialState(),
    reducers: {
        // 保存搜索结果
        saveResults: searchEntityAdaptor.addMany,
        // 清空搜索结果
        clearResults: searchEntityAdaptor.removeAll,
    },
});

// 导出搜索结果状态选择器
export const searchResultSelectors =
    searchEntityAdaptor.getSelectors<AppState>(
        (state:any) => state.searchReducer
    );

export const { saveResults, clearResults } = actions;
export default searchReducer;